#include <gtk/gtk.h>
#include <stdlib.h>
#include <locale.h>

#include "callbacks.h"
#include "config.h"
#include "loop.h"
#include "nls.h"
#include "settings.h"
#include "views.h"
#include "ttorrent.h"

void restore_session(TTorrent * tt)
{
  TSettings * ts = tt->settings;
  GKeyFile * kf = parse_settings(tt->conf_dir);
  gchar **groups = g_key_file_get_groups(kf, NULL);
  gchar **g = groups;
  gint * pri;
  gint value;
  gdouble dvalue;
  gchar * filename;
  GError * error;
  TSaveState tss;

  ts->save_dir = g_key_file_get_string(kf, "SESSION", "save_dir", NULL);
  if(ts->save_dir == NULL) ts->save_dir = g_get_current_dir();
  dvalue = g_key_file_get_double(kf, "SESSION", "seed_ratio", NULL);
  ts->seed_ratio = ( dvalue != 0.0 ? dvalue : 1.5 );

  value = g_key_file_get_integer(kf, "SESSION", "port_min", NULL);
  ts->port_min = ( value != 0 ? value : 6881);
  value = g_key_file_get_integer(kf, "SESSION", "port_max", NULL);
  ts->port_max = ( value != 0 ? value : 6999);
  value = g_key_file_get_integer(kf, "SESSION", "active_torrents", NULL);
  ts->active_torrents = ( value != 0 ? value : 2);
  value = g_key_file_get_integer(kf, "SESSION", "save_frequency", NULL);
  ts->save_freq = ( value > 0 ? value : 600);
  value = g_key_file_get_integer(kf, "SESSION", "max_open_connections", NULL);
  ts->connections = ( value > 0 ? value : 128);
  value = g_key_file_get_integer(kf, "SESSION", "max_uploads", NULL);
  ts->uploads = ( value > 0 ? value : 8 );
  value = g_key_file_get_integer(kf, "SESSION", "download_speed_limit", NULL);
  ts->down_speed = ( value > 0 ? 1024*value : -1 );
  value = g_key_file_get_integer(kf, "SESSION", "upload_speed_limit", NULL);
  ts->up_speed = ( value > 0 ? 1024*value : -1 );
  value = g_key_file_get_integer(kf, "SESSION", "use_dht", NULL);
  ts->use_dht = ( value != 0 ? value : 2 );
  value = g_key_file_get_integer(kf, "SESSION", "use_pex", NULL);
  ts->use_pex = ( value != 0 ? value : 1 );

  init_session(tt);

  while(*g != NULL)
  {
    if ( g_str_equal ("SESSION", *g ) )
    {
      ++g;
      continue;
    }

    tss.priorities = g_key_file_get_string(kf, *g, "priorities", NULL);
    value = g_key_file_get_integer(kf, *g, "downloaded_h", NULL);
    tss.downloaded = 1024*1024*1024*value;
    value = g_key_file_get_integer(kf, *g, "downloaded_l", NULL);
    tss.downloaded += value;
    value = g_key_file_get_integer(kf, *g, "uploaded_h", NULL);
    tss.uploaded = 1024*1024*1024*value;
    value = g_key_file_get_integer(kf, *g, "uploaded_l", NULL);
    tss.uploaded += value;
    filename = g_build_filename(tt->conf_dir, *g, NULL);
    if ( !add_torrent(tt, filename, &tss) )
      g_message(_("Can't add torrent %s\n"), *g);
    g_free(filename);
    ++g;
  }
  g_strfreev(groups);
}

update_tooltip(GtkStatusIcon * icon, TStatus * ts)
{
  if (icon == NULL) return;
  gchar buf[400];
  g_snprintf(buf, sizeof(buf), _("Download speed: %.1f\nUpload speed: %.1f\nConnections:%d"),
    ts->down_speed, ts->up_speed, ts->num_peers);
  gtk_status_icon_set_tooltip(icon, buf);
}

void update_settings(TTorrent * tt)
{
  GKeyFile * kf = g_key_file_new();
  TSettings * ts = tt->settings;
  GError * error = NULL;

  g_key_file_set_comment(kf, NULL, NULL, "Autogenerated file. DO NOT EDIT", &error);

  if(error)
  {
    g_message(error->message);
    g_key_file_free(kf);
    return;
  }

  g_key_file_set_string(kf, "SESSION", "save_dir", ts->save_dir);
  g_key_file_set_double(kf, "SESSION", "port_min", ts->seed_ratio);

  g_key_file_set_integer(kf, "SESSION", "port_min", ts->port_min);
  g_key_file_set_integer(kf, "SESSION", "port_max", ts->port_max);
  g_key_file_set_integer(kf, "SESSION", "active_torrents", ts->active_torrents);
  g_key_file_set_integer(kf, "SESSION", "save_frequency", ts->save_freq);
  g_key_file_set_integer(kf, "SESSION", "max_connections", ts->connections);
  g_key_file_set_integer(kf, "SESSION", "max_uploads", ts->uploads);

  g_key_file_set_integer(kf, "SESSION", "download_speed_limit",
    ( ts->down_speed > 0 ? ts->down_speed / 1024 : -1));
  g_key_file_set_integer(kf, "SESSION", "upload_speed_limit",
    ( ts->up_speed > 0 ? ts->up_speed / 1024 : -1));

  g_key_file_set_integer(kf, "SESSION", "use_dht", ts->use_dht);
  g_key_file_set_integer(kf, "SESSION", "use_pex", ts->use_pex);

  query_torrents(tt->torrents_view, kf);
  save_settings(kf, tt->conf_dir);
  tt->timer = 0;
  g_key_file_free(kf);
}

gboolean
timeout_func(gpointer data)
{
  TTorrent * tt = (TTorrent *) data;
  TStatus ts;

  main_loop(tt);
  query_session_status(tt->sess, &ts);
  update_statusbar(tt->statusbar, &ts);
  update_tooltip(tt->icon, &ts);

  if(tt->timer > tt->settings->save_freq) update_settings(tt);
  else ++tt->timer;

  return TRUE;
}

void input_func
( gpointer          data,
  gint              source,
  GdkInputCondition condition
)
{
  gchar * fname = socket_receive(source);
  g_printerr("%s\n", fname);
  add_torrent((TTorrent *) data, fname, NULL);
  g_free(fname);
}

int
main (int argc, char* argv[])
{
    gint arg_c = argc;
    gchar ** arg_v = argv;
    gchar ** files = parse_command_line(&arg_c, &arg_v);
    TTorrent * ttorrent = g_slice_new0(TTorrent);
    ttorrent->conf_dir = g_build_filename (g_get_home_dir(), ".ttorrent", NULL);
    gchar * fname = g_build_filename (ttorrent->conf_dir, "ttorrent_sock", NULL);
    gint sock = init_socket(fname, files);

    if (sock < 0)
    {
      g_slice_free(TTorrent, ttorrent);
      exit(0);
    }

    ttorrent->settings = g_slice_new0(TSettings);

    gtk_init (&argc, &argv);
#ifdef ENABLE_NLS
    setlocale(LC_MESSAGES, "");
    bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
#endif
    //ttorrent->keyfile = parse_settings(ttorrent->conf_dir, ttorrent->conf_file);
    /* create the main, top level, window */
    create_window(ttorrent);
    restore_session(ttorrent);
    if(files) add_torrents(ttorrent, files);

    gdk_input_add(sock, GDK_INPUT_READ, input_func, ttorrent );
    g_timeout_add (500, timeout_func, ttorrent);

    /* start the main loop */
    gtk_main ();

    close_socket(sock, fname);

    close_session(ttorrent);

    update_settings(ttorrent);

    g_free(ttorrent->conf_dir);
    g_free(ttorrent->settings->save_dir);
    g_slice_free(TSettings, ttorrent->settings);
    g_slice_free(TTorrent, ttorrent);

    return 0;
}
